package vben.core.module.ass.oss.main;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vben.core.common.mvc.api.R;
import vben.core.common.mvc.dao.JdbcDao;
import vben.core.common.mvc.dao.Sqler;
import vben.core.framework.cache.RedisHandler;
import vben.core.framework.security.authz.JwtHandler;
import vben.core.framework.security.pojo.Zuser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("ass/oss/main")
@Api(tags = {"文件存储"})
public class AssOssMainApi {

    @GetMapping
    @ApiOperation("查询存储分页")
    public R get(String name) {
        Sqler sqler = new Sqler("t.name,t.id,t.type,t.crtim", "ass_oss_main");
        sqler.addInnerJoin("f.zsize,f.service,f.path", "ass_oss_file f", "f.id=t.filid");
        sqler.addLeftJoin("u.name crman", "sys_org_user u", "u.id=t.crmid");
        sqler.addLike("t.name", name);
        sqler.addOrder("t.crtim desc");
        return R.ok(jdbcDao.findPageData(sqler));
    }

    @GetMapping("download")
    @ApiOperation("附件下载")
    public void download(String table, String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        service.downloadFile(request,response,table,id);
    }

    @GetMapping("show")
    @ApiOperation("附件图片预览")
    public void show(String token, String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        if(StrUtil.isBlank(token)){
            return;
        }
        String uuid = jwtHandler.getClaims(token.substring(7)).getId();
        Zuser zuser = (Zuser) redisHandler.get("online-key:"+uuid);
        if(zuser!=null){
            service.downloadFile(request,response,null,id);
        }
    }

    @PostMapping(value="upload",produces = "text/html;charset=UTF-8")
    @ApiOperation("附件上传")
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
        Zfile zfile = service.uploadFile(file);
        return "{\"id\":\"" + zfile.getId() + "\",\"path\":\"" + zfile.getPath() + "\",\"filid\":\"" + zfile.getFilid() + "\",\"name\":\"" + zfile.getName() + "\",\"size\":\"" +  zfile.getSize() + "\"}";
    }

    @DeleteMapping("{ids}")
    @ApiOperation("删除文件")
    public R delete(@PathVariable String[] ids) {
        service.delete(ids);
        return R.ok();
    }

    @Autowired
    private JwtHandler jwtHandler;

    @Autowired
    private RedisHandler redisHandler;

    @Autowired
    private JdbcDao jdbcDao;

    @Autowired
    private AssOssMainService service;

}
